package com.cml.rpc.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 使用netty作为rpc通信服务器，用NIO替换开始BIO
 * @author cml
 * @create 2021/7/21 13:20
 */
public class NettyRpcServer implements RpcServer{
    private ServiceProvider serviceProvider;

    public NettyRpcServer(){}

    public NettyRpcServer(ServiceProvider serviceProvider) {
        this.serviceProvider = serviceProvider;
    }

    @Override
    public void start(int port) {
        // netty 服务线程组boss负责建立连接，work负责具体的工作
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        System.out.println("--------netty服务端启动-------");
        try {
            // 初始化服务端引导类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // group设置线程组
            serverBootstrap.group(bossGroup, workGroup)
                    // 设置通道类型
                    .channel(NioServerSocketChannel.class)
                    // 设置handler在每个客户端连接时使用
                    .childHandler(new NettyServerInitializer(serviceProvider));
            // 绑定端口建立连接
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            // 死循环监听
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    @Override
    public void stop() {

    }
}
